﻿#pragma once

#pragma warning(disable : 4996)

#include <StrUtil.h>
#include <XString.h>
#include <IXDraw.h>
#include <IXImageDraw.h>
#include <IXColorDraw.h>

namespace ParseHelper
{

    __inline BOOL ParseColor(IN LPCTSTR szValue, OUT COLORREF& clrResult)
    {
        unsigned int Red = 0;
        unsigned int Green = 0;
        unsigned int Blue = 0;
        int nResult = _sntscanf(szValue + 1, 6, _T("%02x%02x%02x"), &Red, &Green, &Blue);
        if(nResult != 3)
            return FALSE;

        clrResult = RGB(Red, Green, Blue);
        return TRUE;
    }

    __inline BOOL ParseImageDrawParams(IN LPCTSTR szValue, OUT ImageDrawParams& params)
    {
        XString strValue(szValue);
        XString strToken;
        size_t handle = 0;

        memset(&params, 0, sizeof(params));

        DWORD* pDwData = (DWORD*)&params;
        size_t nCount = 0;
        while(StrUtil::NextToken(strValue, handle, _T(","), strToken, TRUE))
        {
            pDwData[nCount] = _ttoi(strToken.GetData());
            ++ nCount;
        }
        return TRUE;
    }

    __inline IXDraw* ParseBackground(IN LPCTSTR szValue)
    {
        IXDraw* pResultBkg = NULL;
        XString strBkg(szValue);
        if(strBkg.size() > 2)
        {
            if(strBkg.c_str()[0] == _T('#'))
            {
                COLORREF clrStart, clrEnd;
                if(ParseHelper::ParseColor(strBkg.GetData(), clrStart))
                {
                    XInstPtr<IXColorDraw> pBkg;
                    size_t pos = strBkg.find(_T(";#"));
                    if(pos != XString::npos && ParseHelper::ParseColor(strBkg.c_str() + pos + 1, clrEnd))
                        pBkg->put_GradientColor(clrStart, clrEnd);
                    else
                        pBkg->put_Color(clrStart);
                    if(strBkg.find(_T("vert")) != XString::npos)
                        pBkg->put_Direction(FALSE);
                    else if(strBkg.find(_T("horz")) != XString::npos)
                        pBkg->put_Direction(TRUE);
                    pResultBkg = Util::QueryIntf<IXDraw>((IXColorDraw*)pBkg);
                    if(pResultBkg != NULL)
                        pResultBkg->AddRef();
                }
            }
            else
            {
                XInstPtr<IXImageDraw> pDraw;
                if(SUCCEEDED(pDraw->put_ImagePath(strBkg.GetData())))
                {
                    pResultBkg = Util::QueryIntf<IXDraw>((IXImageDraw*)pDraw);
                    if(pResultBkg != NULL)
                        pResultBkg->AddRef();
                }
            }
        }
        return pResultBkg;
    }

}